//
//  RootViewController.m
//  CocoaBean
//
//  Created by sleeper on 5/26/10.
//  Copyright __MyCompany__ 2010. All rights reserved.
//

#import "GDataOAuthViewControllerTouch.h"

#import "AKRequestHeader.h"
#import "AKMiniblogEntry.h"

#import "AKAppController.h"

#import "AKMiniblogViewController.h"

NSString * const _kAKMiniblogArchiveName = @"miniblogArchive.plist";

@interface AKMiniblogViewController () <AKRequestDelegate>
@property (nonatomic, copy) NSArray *miniblogEntries;
@end

@implementation AKMiniblogViewController

@synthesize miniblogEntries = _miniblogEntries;

- (id)init
{
	if ((self = [super initWithStyle:UITableViewStylePlain])) {
		self.title = NSLocalizedString(@"Miniblog", @"Miniblog");
	}
	return self;
}

- (NSString *)_archivePath
{
	return [[AKAppController documentFolderPath] stringByAppendingPathComponent:_kAKMiniblogArchiveName];
}

#pragma mark -

- (void)viewDidLoad
{
	[super viewDidLoad];
	
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Post Saying", @"Post Saying")
																			   style:UIBarButtonItemStyleBordered 
																			  target:self
																			  action:@selector(_post)] autorelease];
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Reload", @"Reload")
																			  style:UIBarButtonItemStyleBordered
																			 target:self
																			 action:@selector(reload)] autorelease];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	if (_miniblogEntries == nil) {
		NSString *archivePath = [self _archivePath];
		if ([[NSFileManager defaultManager] fileExistsAtPath:archivePath]) {
			_miniblogEntries = [[NSKeyedUnarchiver unarchiveObjectWithFile:archivePath] retain];
		}
	}
	[self.tableView reloadData];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_miniblogEntries count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	// Configure the cell.
	AKMiniblogEntry *entry = [_miniblogEntries objectAtIndex:indexPath.row];
	cell.textLabel.text = [entry title];
	cell.detailTextLabel.text = [entry authorName];

    return cell;
}

#pragma mark -

- (void)reload
{
	NSString * userId = [AKAppController sharedAppController].userId;
	if ([userId length] > 0) {
		AKRequest *request = [AKRequest requestWithType:kAKRequestTypeMiniblogEntries extraInfo:userId];
		[request addIntParameter:1 forKey:kAKRequestParameterKeyStartIndex];
		[request addIntParameter:50 forKey:kAKRequestParameterKeyMaxResults];
		request.identifier = @"miniblog";
		[[AKAppController sharedAppController].requestManager runRequest:request delegate:self];
	}
}

- (void)archiveMiniblogs
{
	if ([_miniblogEntries count] > 0) {
		NSString *filePath = [self _archivePath];
		if (![NSKeyedArchiver archiveRootObject:_miniblogEntries toFile:filePath]) {
			NSLog(@"Cannot archive miniblogs to:%@", filePath);
		}
	}
}

- (void)_post
{
	// TODO: posting doesn't work yet
	NSString *saying = @"Hello From My iPhone";	
	AKRequest *request = [AKRequest requestWithType:kAKRequestTypePostSaying extraInfo:saying];
	if (request) {
		request.identifier = @"saying";
		[[AKAppController sharedAppController].requestManager runRequest:request delegate:self];
	}
	else {
		NSLog(@"Error posting");
	}
}

#pragma mark AKRequestDelegate

- (void)request:(AKRequest*)request didFinishWithData:(NSData *)data
{
	if ([request.identifier isEqualToString:@"miniblog"]) {
		NSString *responseString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
		id responseInfo = [responseString JSONValue];
		
		NSArray *newMiniblogs = [responseInfo objectForKey:@"entry"];
		self.miniblogEntries = [AKMiniblogEntry entriesWithDictionaries:newMiniblogs];
		[self.tableView reloadData];
	}
	else if ([request.identifier isEqualToString:@"saying"]) {
		NSString * string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
		NSLog(@"Responce:%@", string);
		
		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Saying Posted!", @"Saying posted.")
															message:nil
														   delegate:nil
												  cancelButtonTitle:NSLocalizedString(@"OK", @"OK")
												  otherButtonTitles:nil];
		[alertView show];
		[alertView autorelease];
	}
}

- (void)request:(AKRequest*)request didFailWithError:(NSError*)error
{
	NSLog(@"Request:%@ failedWithError:%@", request, error);
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc
{
	[[AKAppController sharedAppController].requestManager removeDelegate:self];

	AK_RELEASE(_miniblogEntries);
    [super dealloc];
}

@end

